<template>
	<view class="content">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">添加设备</block>
		</cu-custom>
		<view class="login-btn">
			<text>
				请网页输入相机IP登录设备，然后进入【更多参数】【关于】，获取<b>相机序列号</b>和对应<b>二维码</b>进行添加，如下图：
				<!-- <text @tap="handAdd" class="text-link">手动添加</text> -->
			</text>
		</view>

		<view class="flex padding justify-center image-bg">
			<!-- <image mode="aspectFill" src="https://hafcapp.oss-cn-shanghai.aliyuncs.com/cs/background_add_device_small.jpg?Expires=1868637600&OSSAccessKeyId=LTAIA9VLEk1xfvBJ&Signature=oaC8HEU0BSjSe8S379WBcxlwOzA%3D"></image> -->
			<image mode="aspectFit"
				src="https://hafcapp.oss-cn-shanghai.aliyuncs.com/cs/device_code1.png?Expires=2846944800&OSSAccessKeyId=LTAI5tRYmxZffryFSUt8TtZ3&Signature=N9my5w9t412zqidI%2FZF1nQMduBg%3D">
			</image>
		</view>
		<view class="login-btn">
			<button class="landing" @click="startScan" type="primary">扫码添加</button>
		</view>
		<view class="login-btn">
			<button class="landing" @click="handAdd" type="">手动添加</button>
		</view>
		<!-- <view class="login-btn">
			<button class="landing" @click="handToHome" type="default">直接跳过</button>
		</view> -->

		<view class="cu-modal" :class="modalName=='InputDialog'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">添加设备</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding dialog-bg">
					<view class="login-input">
						<input type="text" @input="input" v-model="deviceId"
							placeholder="请输入序列号,例:111111-222222-333333" />
					</view>
					<view class="login-input">
						<input type="text" @input="input" v-model="deviceName" placeholder="请输入设备名,例:公司大门进口" />
					</view>
					<text class="notice-color">{{erroNotice}}</text>
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green" @tap="hideModal">取消</button>
						<button class="cu-btn bg-green margin-left" @tap="startIncrease">确定</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var jssdk = require('components/node_modules/jweixin-module');
	// var jssdk = require('jweixin-module')
	export default {
		data() {
			return {
				modalName: null,
				deviceId: '',
				deviceName: '',
				erroNotice: '',
				link: '',
				showDeviceId: false,

			}
		},
		onLoad(options) {
			console.log("options", options)
			if (typeof(options.link) != 'undefined') {
				this.link = options.link
			}
			let pageUrl = location.href.split('#')[0]
			// let pageUrl="https://kq.lsyat.com/yundianmao/adm"
			// pageUrl=encodeURIComponent(pageUrl)
			console.log("pageUrl:",pageUrl)
			uni.request({
				url: this.$constant.BASEURL + this.$constant.GET_CONFIG,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				
				data: {
					url: pageUrl
				},
				success: (res) => {
					//res.data={singnature: "", appId: "", nonceStr: "mKG2AgugJvkX7YPxkYsAsSUAGFr7Ezs8", timestamp: 1715760665}
					console.log('获取sdk权限：', res)
					var param = res.data
					if (res.statusCode == 200) {
						jssdk.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							// appId: 'wx4dcf50b8f0685b81',
							// timestamp: 1715833790,
							// nonceStr: '111111',
							// signature: '3ae2ed05ef8cd227c6911845d2ee5f490fb82a6f',
							appId: param.appId, // 必填，公众号的唯一标识
							timestamp: param.timestamp, // 必填，生成签名的时间戳
							nonceStr: param.nonceStr, // 必填，生成签名的随机串
							signature: param.singnature, // 必填，签名
							jsApiList: ['scanQRCode'], // 必填，需要使用的JS接口列表
						});

						jssdk.ready(function() { // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
							console.log("jssdk ready...")
							// jssdk.checkJsApi({ // 判断当前客户端版本是否支持指定JS接口
							// 	jsApiList: ['scanQRCode'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
							// 	success: function(res) {
							// 		if (typeof WeixinJsSDK.callback == 'function') {
							// 			WeixinJsSDK.callback()
							// 		}
							// 		// 以键值对的形式返回，可用的api值true，不可用为false
							// 		// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
							// 	}
							// });
						});
						jssdk.error(function(res) { 
							// config信息验证失败会执行error函数，如签名过期导致验证失败具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
							console.log("jssdk报错：",res)
							// uni.showToast({
							// 	title:res.errMsg,
							// 	icon:'error'
							// })
						});


					}
				}
			})
		},
		methods: {
			startScan() {
				this.deviceId = ''
				this.showDeviceId = true
				this.erroNotice = ''
				//测试时使用
				// if(getApp().globalData.debug){
				// 	this.modalName = 'InputDialog'
				// 	console.log("测试时return...")
				// 	return
				// }
				// 只允许通过相机扫码
				var that = this;
				console.log('jssdk', jssdk.scanQRCode)
				jssdk.scanQRCode({
					needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode"], // 可以指定扫二维码还是一维码"barCode"，默认二者都有
					success: function(res) {
						console.log("已扫码，", res)
						var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
						//var params = result;
						var sn = result;
						if (sn != null && typeof(sn) != 'undefined') {
							that.deviceId = sn
							that.modalName = 'InputDialog'
						} else {
							uni.showToast({
								title: "无效二维码"
							})
						}
					},
					fail: function(res) {
						console.log('扫描失败!' + res.errMsg);
					},
					complete: function(){
						console.log("扫码调用完成！")
					}
				});
			},
			handToHome() {
				uni.switchTab({
					url: '../attendance/attendance'
				});
			},
			handAdd() {
				this.deviceId = ''
				this.erroNotice = ''
				this.showDeviceId = true
				this.modalName = 'InputDialog'
			},
			input(res) {
				this.erroNotice = ''
			},
			hideModal(e) {
				this.modalName = null
			},
			startIncrease() {
				console.log(this.deviceName)

				if (this.deviceId == '') {
					this.erroNotice = '请输入序列号'
					return
				}
				if (this.deviceName == '') {
					this.erroNotice = '请输入设备名'
					return
				}
				var that = this
				that.modalName = ''
				uni.request({
					url: this.$constant.BASEURL + this.$constant.ADD_DEVICE,
					method: "POST",
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						username: getApp().globalData.username,
						token: getApp().globalData.token,
						villageno: getApp().globalData.orgcode,
						deviceno: this.deviceId,
						addrname: this.deviceName
					},
					success: (res) => {
						console.log(res.data)
						if (res.data.code == 0) {
							uni.showToast({
								title: "添加成功",
							})
							// uni.navigateTo({
							// 	url: 'setting?deviceId=' + that.deviceId + '&link=' + this.link
							// })
							if(this.link=='first'){
								uni.switchTab({
								    url: '../attendance/attendance'
								});
							}else{
								uni.navigateBack({
									delta:1
								})
							}
						} else {
							uni.showToast({
								title: res.data.message,
								icon: "none"
							})
						}
					}
				});
			}
		}
	}
	/**
	 * 通过get链接获取到参数
	 */
	export const GetRequestParameters = (link) => {
		//通过？截取字符串
		var index = link.indexOf("?")
		var url = link.substr(index, link.length)
		//通过&获取参数
		let theRequest = new Object();
		if (url.indexOf("?") != -1) {
			let str = url.substr(1);
			let strs = str.split("&");
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
</script>

<style>
	.image-bg {
		/* height: 50%; */
	}

	.login-btn {
		padding: 10upx 20upx;
		margin-top: 20upx;
	}

	.landing {
		height: 84upx;
		line-height: 84upx;
		border-radius: 44upx;
		font-size: 32upx;
		background: linear-gradient(left, #5599ff, #5599ff);
	}

	.dialog-bg {
		background-color: #FFFFFF;
	}

	.login-input input {
		background: #F2F5F6;
		font-size: 28upx;
		padding: 10upx 25upx;
		height: 80upx;
		line-height: 62upx;
		border-radius: 8upx;
	}

	.login-input {
		padding: 10upx 20upx;
	}

	.notice-color {
		color: #DD524D;
	}

	.text-link {
		font-size: 32upx;
		color: #007AFF;
		text-decoration: underline;
	}


	.reader-box {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}

	.reader {
		width: 100%;
		// width: 540rpx;
		// height: 540rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
</style>